package com.sw.c.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

@Api(tags = "视频相关接口")
@RestController
@RequestMapping("/sp")
public class VideoController {

    @ApiOperation("视频播放")
    @GetMapping("/video/play")
    public ResponseEntity<byte[]> playVideo() throws IOException {
        String videoPath = getClass().getResource("/static/001.mp4").toExternalForm();
        System.out.println("Video Path: " + videoPath);
        Resource videoFile = new ClassPathResource("static/001.mp4");
        InputStream inputStream = videoFile.getInputStream();

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[4096];
        int bytesRead;
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, bytesRead);
        }

        byte[] videoBytes = outputStream.toByteArray();

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentLength(videoBytes.length);

        return new ResponseEntity<>(videoBytes, headers, HttpStatus.OK);
    }

}
